package com.lz.sports.service

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner

object ServiceStatusManager {

    private val observers = ArrayList<StatusObserver>()

    var isNetwork: Boolean = false
        private set

    fun observe(owner: LifecycleOwner, observer: StatusObserver) {
        if (owner.lifecycle.currentState == Lifecycle.State.DESTROYED) return
        observers.add(observer)
        owner.lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    observers.remove(observer)
                }
            }
        })
    }

    fun changeStatus(status: Boolean) {
        if (isNetwork != status) {
            isNetwork = status
            observers.forEach { it.onStatusChanged(status) }
        }
    }

    interface StatusObserver {

        fun onStatusChanged(status: Boolean)
    }
}